package xyz.icxl.android.architecture.helper

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import xyz.icxl.android.architecture.R

/**
 * # [TabLayout] 配合 [ViewPager2] 工具
 * - author：`cxl`
 * - date: `2023/2/1`
 */
object MaterialTlVP2Helper {
    data class Item(
        /**
         * 顶部标题
         */
        val title: CharSequence,
        val fragment: Fragment
    )

        /**
         * 组合使用
         * @param fragmentActivity FragmentActivity
         * @param tabLayout TabLayout
         * @param viewPager2 ViewPager2
         * @param pageList pageList by MutableList<Item>
         */
        fun combinedUse(
        fragmentActivity: FragmentActivity,
        tabLayout: TabLayout,
        viewPager2: ViewPager2,
        pageList: MutableList<Item>
    ) {
        viewPager2.adapter = TlVP2Adapter(fragmentActivity, pageList)
        TabLayoutMediator(tabLayout, viewPager2) { tab, position ->
            tab.text = pageList[position].title

        }.attach()
    }


    private class TlVP2Adapter(
        fragmentActivity: FragmentActivity,
        private val pageList: MutableList<Item>
    ) : FragmentStateAdapter(fragmentActivity) {
        override fun getItemCount(): Int = pageList.size

        override fun createFragment(position: Int): Fragment = pageList[position].fragment
    }
}